package com.financing.wap.weixin.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.weixin.handle.CreatePosterHandler;
import com.financing.wap.weixin.handle.DefaultHandler;
import com.financing.wap.weixin.handle.MessageHandler;
import com.financing.wap.weixin.handle.TextHandler;
import com.financing.wap.weixin.handle.event.LocationEvent;
import com.financing.wap.weixin.handle.event.ScanEvent;
import com.financing.wap.weixin.handle.event.SubscribeEvent;
import com.financing.wap.weixin.handle.event.UnsubscribeEvent;
import com.financing.wap.weixin.service.CoreService;
import com.financing.wap.weixin.util.MessageUtil;
import com.financing.wap.weixin.util.SignUtil;

@Service("coreService")
public class CoreServiceImpl implements CoreService {

	@Autowired
	private SubscribeEvent subscribeEvent;

	@Autowired
	private UnsubscribeEvent unsubscribeEvent;

	@Autowired
	private LocationEvent locationEvent;

	@Autowired
	private TextHandler textHandler;

	@Autowired
	private DefaultHandler defaultHandler;


	@Autowired
	private CreatePosterHandler createPosterHandler;
	
	@Autowired
	private ScanEvent scanEvent;

	Map<String, Object> objectMap;

	Logger logger = Logger.getLogger(getClass());

	public static final String appid = PropertiesUtils.getValue("appid");
	
	public static final String secret = PropertiesUtils.getValue("secret");
	
	private final String redirect_uri = PropertiesUtils.getValue("wszl_baseurl")+"/wxapi/weixin/opencallback";
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, String> processRequest(HttpServletRequest request) {
		logger.info("In CoreServiceImpl processRequest Begin!");
		String respMessage = null;
		Map<String, String> requestMap = new HashMap<String, String>();
		try {

			// xml请求解析成Map
			requestMap = MessageUtil.parseXml(request);
			// 消息类型
			String msgType = requestMap.get("MsgType");
			logger.info("In CoreServiceImpl processRequest msgType:" + msgType+"===MsgId:"+requestMap.get("MsgId"));
			
			
			// 根据消息类型 -获取消息对象
			MessageHandler handler = getBean(msgType, requestMap);

			// 如果获取的对象为空，赋值为defaultHandler
			if (handler == null) {
				handler = defaultHandler;
			}
			
			// 调用消息处理
			respMessage = handler.messageHandler(requestMap);

			requestMap.put("respMessage", respMessage);

		} catch (Exception e) {
			logger.error("error CoreServiceImpl processRequest!", e);

		}
		logger.info("In CoreServiceImpl processRequest end!");
		return requestMap;
	}

	@PostConstruct
	public void initObjectMap() {
		logger.info("In CoreServiceImpl initObjectMap Begin!");
		objectMap = new HashMap<String, Object>();

		Map<String, Object> eventMap = new HashMap<String, Object>();
		eventMap.put(MessageUtil.EVENT_TYPE_UNSUBSCRIBE, unsubscribeEvent);
		eventMap.put(MessageUtil.EVENT_TYPE_SUBSCRIBE, subscribeEvent);
		eventMap.put(MessageUtil.EVENT_TYPE_SCAN, scanEvent);
		eventMap.put(MessageUtil.EVENT_TYPE_LOCATION, locationEvent);
		
		Map<String, Object> clickEventMap = new HashMap<String, Object>();
		clickEventMap.put(MessageUtil.EVENT_TYPE_CLICK_WXXF_SCHB,
				createPosterHandler);
		eventMap.put(MessageUtil.EVENT_TYPE_CLICK, clickEventMap);

		objectMap.put(MessageUtil.REQ_MESSAGE_TYPE_EVENT, eventMap);
		objectMap.put(MessageUtil.REQ_MESSAGE_TYPE_TEXT, textHandler);

		logger.info("In CoreServiceImpl initObjectMap end!");
	}

	/**
	 * 根据消息类型获取实例对象
	 * 
	 * @param msgType
	 * @return MessageHandler
	 */
	public MessageHandler getBean(String msgType, Map<String, String> requestMap) {
		Object object = objectMap.get(msgType);
		if (object == null) {
			logger.info("In CoreServiceImpl processRequest objectMapForMsgType is null");
			return defaultHandler;
		}
		// 如果是map对象-找子对象 （否则调用消息处理）
		if (object instanceof Map) {

			String eventStr = requestMap.get("Event");

			logger.info("In CoreServiceImpl processRequest Event:" + eventStr);

			Map<?, ?> eventMap = (Map<?, ?>) object;

			Object eventObj = eventMap.get(eventStr);

			// 如果是map对象-找子对象 （否则调用消息处理）
			if (eventObj instanceof Map) {
				String eventKey = requestMap.get("EventKey");
				logger.info("In CoreServiceImpl processRequest EventKey:"
						+ eventKey);
				Map<?, ?> clickMap = (Map<?, ?>) eventObj;
				Object clickObj = clickMap.get(eventKey);
				if (clickObj instanceof MessageHandler) {
					return (MessageHandler) clickObj;
				}
			} else if (eventObj instanceof MessageHandler) {

				return (MessageHandler) eventObj;
			}
		} else if (object instanceof MessageHandler) {

			return (MessageHandler) object;
		}

		return null;
	}

	@Override
	public boolean checkRequest(HttpServletRequest request) {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");

		return SignUtil.checkSignature(signature, timestamp, nonce);

	}

	@SuppressWarnings("deprecation")

	@Override
	public void processSubsequentRequest(Map<String, String> requestMap) {
		logger.info("In CoreServiceImpl processSubsequentRequest Begin!");
		try {

			String msgType = requestMap.get("MsgType");
			// 根据消息类型 -获取消息对象
			MessageHandler handler = getBean(msgType, requestMap);

			// 如果获取的对象为空，赋值为defaultHandler
			if (handler == null) {
				handler = defaultHandler;
			}

			// 调用消息处理
			handler.messageSubsequentHandler(requestMap);

		} catch (Exception e) {
			logger.error("error CoreServiceImpl processSubsequentRequest!", e);

		}
		logger.info("In CoreServiceImpl processSubsequentRequest end!");
	}

}
